#include <esp_log.h>
#include "sync_time.h"

static const char *TAG = "Time";
#define DEBUG 0

void SntpTime::init()
{
    esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);

    esp_sntp_setservername(0, "cn.pool.ntp.org");
    esp_sntp_setservername(1, "pool.ntp.org");
    esp_sntp_setservername(2, "ntp1.aliyun.com");
    esp_sntp_setservername(3, "ntp2.aliyun.com");
    esp_sntp_setservername(4, "ntp3.aliyun.com");
    esp_sntp_setservername(5, "ntp4.aliyun.com");

    setenv("TZ", "CST-8", 1);
    tzset(); // update timezone

    esp_sntp_init();
    do
    {
        vTaskDelay(100 / portTICK_PERIOD_MS);
    } while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET);
#if DEBUG
    ESP_LOGI(TAG, "Initializing SNTP finished!");
#endif
}
struct tm *SntpTime::asStruct(std::string time_zone_value)
{
    setenv("TZ", time_zone_value.c_str(), 1);
    time_t now;

    ::time(&now);
    // transform to local time
    localtime_r(&now, &time_info);

    return &time_info;
}
uint32_t SntpTime::asTimestamp(std::string time_zone_value)
{
    setenv("TZ", time_zone_value.c_str(), 1);
    time_t now;
    ::time(&now);
    return (uint32_t)now;
}
std::string SntpTime::asString(std::string time_zone_value)
{
    setenv("TZ", time_zone_value.c_str(), 1);

    time_t now;
    struct tm timeinfo;

    ::time(&now);
    // transform to local time
    localtime_r(&now, &timeinfo);
    char *time_str = asctime(&timeinfo);
    if (time_str != NULL)
    {
        // delete the last \n
        time_str[strlen(time_str) - 1] = '\0';
        return std::string(time_str);
    }
    else
    {
        return "ERROR";
    }
}